<template>
  <a-layout style="min-height: 100vh; position: relative">
    <a-layout-sider v-model:collapsed="collapsed" collapsible :width="240" :style="{ background: '#fff', transition: 'all 0.7s ease', willChange: 'width', position: 'fixed', height: '100vh', zIndex: 100 }" :trigger="null">
      <div :style="{ padding: collapsed ? '16px 0' : '16px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '16px', whiteSpace: 'nowrap', overflow: 'hidden' }">
        <img src="https://www.helloimg.com/i/2025/03/12/67d12b55cee33.png" style="height: 32px" />
        <span style="font-size: 16px; font-weight: 500; transition: opacity 0.7s ease;" v-if="!collapsed">J记账运营后台</span>
      </div>
      <a-menu v-model:selectedKeys="selectedKeys" mode="inline" :style="{ background: '#fff' }">
        <template v-for="menu in menuList" :key="menu.key">
          <a-menu-item v-if="!menu.children" :key="menu.key" @click="() => $router.push(menu.path)">
            <template #icon><component :is="menu.icon" /></template>
            <span>{{ menu.title }}</span>
          </a-menu-item>
          <!-- 修改 key 为唯一值，在原 key 后添加 '-sub' -->
          <a-sub-menu v-else :key="menu.key + '-sub'">
            <template #icon><component :is="menu.icon" /></template>
            <template #title>{{ menu.title }}</template>
            <a-menu-item 
              v-for="child in menu.children" 
              :key="child.key" 
              @click="() => $router.push(child.path)"
            >
              <span>{{ child.title }}</span>
            </a-menu-item>
          </a-sub-menu>
        </template>
      </a-menu>
    </a-layout-sider>
    <a-layout>
      <a-layout-header style="background: #fff; padding: 0 16px; display: flex; justify-content: space-between; align-items: center; position: fixed; top: 0; right: 0; left: 240px; zIndex: 99; height: 64px">
        <div style="display: flex; align-items: center; gap: 4px">
          <a-button @click="() => collapsed = !collapsed" type="text">
            <component :is="collapsed ? MenuUnfoldOutlined : MenuFoldOutlined" />
          </a-button>
          <a-breadcrumb style="margin-left: 16px">
            <a-breadcrumb-item>首页</a-breadcrumb-item>
            <a-breadcrumb-item v-for="(item, index) in $route.matched" :key="index">
              {{ item.meta?.title || item.name }}
            </a-breadcrumb-item>
          </a-breadcrumb>
        </div>
        <div style="display: flex; align-items: center; gap: 12px">
          <span style="font-size: 14px; color: rgba(0, 0, 0, 0.65); width: 180px; text-align: center; display: inline-block; text-overflow: ellipsis; overflow: hidden">{{ currentTime }}</span>
          <a-button @click="toggleFullscreen" type="text" style="display: flex; align-items: center">
            <fullscreen-outlined />
          </a-button>
          <a-badge dot :offset="[-4, 4]" :style="{ position: 'relative', zIndex: 1 }">
            <a-button type="text" style="padding: 0 8px; display: flex; align-items: center">
              <bell-outlined />
            </a-button>
          </a-badge>
          <a-dropdown>
    <a-avatar :src="userAvatar" style="margin-left: 4px" />
    <template #overlay>
      <a-menu>
        <a-menu-item key="1">{{ userInfo?.nickname || userInfo?.username }}</a-menu-item>
        <a-menu-item key="2">详情</a-menu-item>
        <a-menu-item key="3" @click="showLogoutConfirm">登出</a-menu-item>
      </a-menu>
    </template>
  </a-dropdown>
        </div>
      </a-layout-header>
      <a-layout-content style="margin: 0 16px; background: #f0f2f5; min-height: calc(100vh - 64px - 70px); position: relative; z-index: 1; overflow-y: auto; margin-top: 64px; margin-left: 256px; margin-right: 16px; height: calc(100vh - 64px - 70px)">
        <div :style="{ padding: '0px', background: '#fff', minHeight: '100%', borderTop: '1px solid #e8e8e8', borderBottom: '1px solid #e8e8e8' }">
          <router-view />
        </div>
      </a-layout-content>
      <a-layout-footer style="text-align: center; height: 48px; display: flex; align-items: center; justify-content: center">
        Ant Design ©2018 Created by Ant UED
      </a-layout-footer>
    </a-layout>
  </a-layout>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { MenuFoldOutlined, MenuUnfoldOutlined, FullscreenOutlined, BellOutlined } from '@ant-design/icons-vue';
import * as Icons from '@ant-design/icons-vue';
import { getMenuTree, logout } from '@/api/auth';
import { Modal } from 'ant-design-vue';
import { initPermissions } from '@/utils/permission';

const selectedKeys = ref(['1']);
const collapsed = ref(false);
const userAvatar = ref('');
const menuList = ref([]);
const currentTime = ref('');

const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'));

const showLogoutConfirm = () => {
  Modal.confirm({
    title: '确认退出登录吗?',
    onOk() {
      return logout().then(() => {
        localStorage.clear();
        window.location.reload();
      });
    }
  });
};

const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen();
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    }
  }
};

const formatMenuData = (data) => {
  return data.map(item => {
    const menuItem = {
      key: item.code || item.id.toString(),
      title: item.title || item.name,
      path: item.path,
      icon: Icons[item.icon || item.meta?.icon] || MenuFoldOutlined,
      component: item.component
    };
    
    if (item.children && item.children.length > 0) {
      menuItem.children = formatMenuData(item.children);
    }
    
    return menuItem;
  });
};

const updateTime = () => {
  const now = new Date();
  const options = { 
    timeZone: 'Asia/Shanghai',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  };
  currentTime.value = now.toLocaleString('zh-CN', options);
};

onMounted(async () => {
  updateTime();
  setInterval(updateTime, 1000);
  
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  userAvatar.value = userInfo.imageUrl || '';
  
  initPermissions(userInfo.perms)
  try {
    const res = await getMenuTree();
    menuList.value = formatMenuData(res);
  } catch (error) {
    console.error('获取菜单失败:', error);
  }
});
</script>

<style scoped>
.logo {
  height: 32px;
  margin: 16px;
  background: rgba(255, 255, 255, 0.3);
}

a-layout-sider {
  transition: all 0.7s ease;
}

a-menu {
  transition: all 0.7s ease;
}

</style>